<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');
/*
 * To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/**
 * Description of dashboard
 *
 * @author Subha Sundar Das (subhasundar.das@gmail.com)
 */
class Listing extends MX_Controller {

	 

	function listing() {
		parent :: __construct();
		$this->load->model(array('admin_member_model','admin_post_model','member/member_model'));

		$this->admin_member_model->check_admin_login();
		$this->template
		->set_layout('default') // application/views/layouts/two_col.php
		->set_theme('admin'); // application/views/layouts/two_col.php
		 
		$this->template->set_partial('nav_bar', 'layouts/nav_bar');
		$this->template->set_partial('side_menu', 'layouts/side_menu');
		$this->template->set_partial('footer','footer/footer');
		 
		 
	}

	function inactive(){
		 
		$status=1;
		$limit = 10;
		$featured=false;
		$search = "";
		 
		if($this->input->post('filter')){
			$filter = $this->input->post('filter');
			 
			switch ($filter) {
				case 'active':
					$status = 51;
					redirect('secure/listing/active');
					break;
				case 'inactive':
					$status = 1;
					redirect('secure/listing/inactive');
					break;
					 
			}
		}

		 
		 
		 
		$data['post'] = $this->admin_post_model->getPost($status = 1,$limit);
		$this->template->build('listing/listing',$data);
		 
	}

	function active(){

		$status=51;
		$limit = 10;
		$featured=false;
		$search = "";

		if($this->input->post('filter')){
			$filter = $this->input->post('filter');
			 
			switch ($filter) {
				case 'active':
					$status = 51;
					redirect('secure/listing/active');
					break;
				case 'inactive':
					$status = 1;
					redirect('secure/listing/inactive');
					break;
			}
		}
		 
		 
		$data['post'] = $this->admin_post_model->getPost($status = 51,$limit);
		$this->template->build('listing/listing',$data);

		 
	}

	function changestatus($status=NULL,$id=NULL){
		if($status == 51){
			$this->admin_post_model->changeStatus($id,$status);
			redirect('secure/listing/active');
			 
		}
		if($status == 1){
			$this->admin_post_model->changeStatus($id,$status);
			redirect('secure/listing/inactive');
		}
	}
	function add(){

		$data['mode'] = "ADD";
		 
		$data['region'] = $this->location_model->getLocation(0,9999);
		$data['category'] = $this->category_model->getCetegory(0,9999);

		$this->template->build('listing/add_listing',$data);
		 
	}

	function submit_business(){

		 
		$this->form_validation->set_rules('business_name', 'Business Name', 'trim|required|xss_clean');

		$this->form_validation->set_rules('category', 'Parent Category', 'trim|required');
		$this->form_validation->set_rules('sub_category', 'Sub-Category', 'trim');
		$this->form_validation->set_rules('keyword[]', 'Keyword', 'trim');

		$this->form_validation->set_rules('region', 'Region', 'trim|required');
		$this->form_validation->set_rules('city', 'City', 'trim|required');

		$this->form_validation->set_rules('address1', 'Address', 'trim|required|xss_clean');
		$this->form_validation->set_rules('zip_code', 'Zip Code', 'trim|required|numeric');
		$this->form_validation->set_rules('fax_no', 'Fax No', 'trim|xss_clean');
		$this->form_validation->set_rules('primary','Phone No', 'trim|required');
		$this->form_validation->set_rules('secondary','Phone No','trim');
		$this->form_validation->set_rules('toll_free', 'Toll Free', 'trim|xss_clean');
		$this->form_validation->set_rules('business_email', 'Business Email', 'trim|required|valid_email');

		$this->form_validation->set_rules('website_url', 'Website Url', 'trim|xss_clean');
		$this->form_validation->set_rules('contact_name', 'Contact Person(1)', 'trim|xss_clean');
		$this->form_validation->set_rules('contact_number', 'Contact Person(1)', 'trim|xss_clean');
		$this->form_validation->set_rules('contact_name_2', 'Contact Person(2)', 'trim|xss_clean');
		$this->form_validation->set_rules('contact_number_2', 'Contact Person(2)', 'trim|xss_clean');
		$this->form_validation->set_rules('description','About Business','trim|xss_clean|required');
		$this->form_validation->set_rules('services','Product and Services','trim|xss_clean|required');



		if ($this->form_validation->run() == TRUE) {
			$post_data = array(
					'mem_id' =>get_session('mem_id'),

					'title' => trim($this->input->post('business_name')),
					'slug' => seoUrl($this->input->post('business_name')),
					'zip_code' => intval($this->input->post('zip_code')),
					'address1' => $this->input->post('address1'),
					'fax' => $this->input->post('fax_no'),
					'phone1' => $this->input->post('primary'),
					'phone2' => $this->input->post('secondary'),
					'toll_free' => $this->input->post('toll_free'),
					'email' => $this->input->post('business_email'),
					'website' => $this->input->post('website_url'),
					'contact_name' => $this->input->post('contact_name'),
					'contact_no' => $this->input->post('contact_number'),
					'contact_name' => $this->input->post('contact_name_2'),
					'contact_no2' => $this->input->post('contact_number_2'),
					'description' => $this->input->post('description'),
					'services' => $this->input->post('services'),
					'lat' => $this->input->post('lat'),
					'long' => $this->input->post('long'),
			);

			//var_dump($post_data);die();

			$this->db->insert('post',$post_data);

			//--Insert Category in Term Table--//

			$bid = $this->_getLastID();

			$post_data1=array(
					'post_id' =>$bid,
					'term' => 'category',
					'caption' => 'Category',
					'value' => intval($_POST['category'])
			);
			$this->db->insert('term',$post_data1);

			//--Insert Sub-Category in Term Table --//
			$post_data2=array(
					'post_id' =>$bid,
					'term' => 'category',
					'caption' => 'Category',
					'value' => intval($_POST['sub_category'])
			);
			$this->db->insert('term',$post_data2);

			//--Insert  Keyword in Term Table--//

			$keyword = $_POST['keyword'];
			foreach ($keyword as $key=>$value) {

				$post_data3= array(
						'post_id' =>$bid,
						'term' => 'keyword',
						'caption' => 'Keyword',
						'value' => $value,
				);


				$this->db->insert('term',$post_data3);
			}
			 
			//--Insert City in Term Table --//
			$post_data4=array(
					'post_id' =>$bid,
					'term' => 'city',
					'caption' => 'City',
					'value' => intval($_POST['city'])
			);
			 
			 
			$this->db->insert('term',$post_data4);
			 
			 
			//--Insert Region in Term Table --//
			$post_data5=array(
					'post_id' =>$bid,
					'term' => 'region',
					'caption' => 'Region',
					'value' => intval($_POST['region'])
			);
			$this->db->insert('term',$post_data5);
			 
			$msgs = "<div class='alert alert-info'> Business Add Successfully</div>";
			$this->session->set_flashdata('message', $msgs);
			redirect('secure/listing/add/');
		}
		else{
			$this->add();
		}



	}

	//--Get Latest Id from Post Table--//
	function _getLastID(){
		$mem_id = intval(get_session('mem_id'));
		$sql = "Select max(id) as id from post where mem_id = $mem_id ";
		$result= $this->db->query($sql)->row();
		if ($result)
		{
			return $result->id;
		}

	}

	function edit($id){
		 
		$data['mode'] = "EDIT";
		 
		//	var_dump($data['mode']);die();
		 
		$data['business'] = getPk('post',$id);
		 
		$data['cityID'] = $this->term_model->getTermValue($id,'city');
		 
		$data['region'] = $this->location_model->getLocation(0,9999);
		 
		// 		/var_dump($data['region']);die();
		$data['regionID'] = $this->term_model->getTermValue($id,'region');
		//	var_dump($data['regionID']);die();
		$data['cityname'] = $this->location_model->getLocation($data['regionID'],9999);
		 
		$data['category'] = $this->category_model->getCetegory(0,9999);
		 
		$array_cat = $this->term_model->getTermCategory($id,'category');
		 
		 
		 
		$pid = $array_cat[0]->value;
		$pid = (int)$pid;
		 
		//$data['subcategory'] = $this->category_model->getChild($pid,9999,FALSE);
		 
		$data['subcategory'] = $this->category_model->getCetegory($array_cat[0]->value,9999);
		 
		 
		$data['catID'] = $pid;
		 
		if(isset($array_cat[1]->value) && $array_cat[1]->value != 0 && $array_cat[1]->value != ''){
			$data['subcatID'] = $array_cat[1]->value;
		}else{
			 
			$data['subcatID'] = 0;
		}
		 
		 
		 
		if($data['subcatID']){
			 
			$data['keyword'] = $this->category_model->getCetegory($data['subcatID'],9999);
			 
		}else{
			 
			$data['keyword'] = 0;
		}
		 
		 
		$data['keywordID'] = $this->term_model->getTermCategory($id,'keyword');

        $data['member'] = $this->admin_member_model->getMembers();

        $sql = "select id,name,description,price from membership where status = 51 order by (price) ASC";
        $result = $this->db->query($sql)->result();

        $data['plan'] = $result;



		 
		$this->template->build('listing/add_listing',$data);
		 
	}

	function update_business($id=0){

		$id = $this->input->post('post_id');

		$this->form_validation->set_rules('business_name', 'Business Name', 'trim|required|xss_clean');

		$this->form_validation->set_rules('category', 'Parent Category', 'trim|required');
		$this->form_validation->set_rules('sub_category', 'Sub-Category', 'trim');
		$this->form_validation->set_rules('keyword[]', 'Keyword', 'trim');

		$this->form_validation->set_rules('region', 'Region', 'trim|required');
		$this->form_validation->set_rules('city', 'City', 'trim|required');

		$this->form_validation->set_rules('address1', 'Address', 'trim|required|xss_clean');
		$this->form_validation->set_rules('zip_code', 'Zip Code', 'trim|required|numeric');
		$this->form_validation->set_rules('fax_no', 'Fax No', 'trim|xss_clean');
		$this->form_validation->set_rules('primary','Phone No', 'trim|required');
		$this->form_validation->set_rules('secondary','Phone No','trim');
		$this->form_validation->set_rules('toll_free', 'Toll Free', 'trim|xss_clean');
		$this->form_validation->set_rules('business_email', 'Business Email', 'trim|required|valid_email');

		$this->form_validation->set_rules('website_url', 'Website Url', 'trim|xss_clean');
		$this->form_validation->set_rules('contact_name', 'Contact Person(1)', 'trim|xss_clean');
		$this->form_validation->set_rules('contact_number', 'Contact Person(1)', 'trim|xss_clean');
		$this->form_validation->set_rules('contact_name_2', 'Contact Person(2)', 'trim|xss_clean');
		$this->form_validation->set_rules('contact_number_2', 'Contact Person(2)', 'trim|xss_clean');
		$this->form_validation->set_rules('description','About Business','trim|xss_clean|required');
		$this->form_validation->set_rules('services','Product and Services','trim|xss_clean|required');



		if ($this->form_validation->run() == TRUE) {
			$post_data = array(
					'mem_id' =>$this->input->post('memname'),
                    'plan' => $this->input->post('plan'),
					'title' => trim($this->input->post('business_name')),
					'slug' => seoUrl($this->input->post('business_name')),
					'zip_code' => intval($this->input->post('zip_code')),
					'address1' => $this->input->post('address1'),
					'fax' => $this->input->post('fax_no'),
					'phone1' => $this->input->post('primary'),
					'phone2' => $this->input->post('secondary'),
					'toll_free' => $this->input->post('toll_free'),
					'email' => $this->input->post('business_email'),
					'website' => $this->input->post('website_url'),
					'contact_name' => $this->input->post('contact_name'),
					'contact_no' => $this->input->post('contact_number'),
					'contact_name' => $this->input->post('contact_name_2'),
					'contact_no2' => $this->input->post('contact_number_2'),
					'description' => $this->input->post('description'),
					'services' => $this->input->post('services'),
                    'verified' => $this->input->post('verified'),
					'lat' => $this->input->post('lat'),
					'long' => $this->input->post('long'),
			);

			//var_dump($business_data);die();

			$this->db->where('id', $id);
			$this->db->update('post', $post_data);

			//--Delete All Existing--//
			$sql = "Delete from term where post_id=$id";
			$this->db->query($sql);

			//--Insert Category in Term Table--//

			$term_data1=array(
					'post_id' =>$id,
					'term' => 'category',
					'caption' => 'Category',
					'value' => intval($_POST['category'])
			);
			$this->db->insert('term',$term_data1);

			//--Insert Sub-Category in Term Table --//
			$term_data2=array(
					'post_id' =>$id,
					'term' => 'category',
					'caption' => 'Category',
					'value' => intval($_POST['sub_category'])
			);
			$this->db->insert('term',$term_data2);

			//--Insert  Keyword in Term Table--//

			$keyword = $_POST['keyword'];
			foreach ($keyword as $key=>$value) {

				$term3_data= array(
						'post_id' =>$id,
						'term' => 'keyword',
						'caption' => 'Keyword',
						'value' => $value,
				);


				$this->db->insert('term',$term3_data);
			}
			 
			//--Insert City in Term Table --//
			$term_data4=array(
					'post_id' =>$id,
					'term' => 'city',
					'caption' => 'City',
					'value' => intval($_POST['city'])
			);
			 
			 
			$this->db->insert('term',$term_data4);
			 
			 
			//--Insert Region in Term Table --//
			$term_data5=array(
					'post_id' =>$id,
					'term' => 'region',
					'caption' => 'Region',
					'value' => intval($_POST['region'])
			);
			$this->db->insert('term',$term_data5);
			 
			$msgs = "<div class='alert alert-info'> Business Update Successfully</div>";
			$this->session->set_flashdata('message', $msgs);
			redirect('secure/listing/edit/'. $id);
		}
		else{
			$this->edit($id);
		}



	}

	function logo($post_id=0)
	{
			
		$sql="select logo from post where id=$post_id";

		$query = $this->db->query($sql);
		if ($query->num_rows() > 0) {
			$row = $query->row();
				
		}
		$data['logo']=$row->logo;
		
		$data['post'] = getPK('post',$post_id);

		$data['post_id'] = $post_id;
		$this->template->build('listing/logo',$data);
	}

	function upload_logo($post_id=0)
	{
		$post_id = $_POST['post_id'];
	
		$filevariable=array_keys($_FILES);
		$userfile=$filevariable[0];
		$image=$_FILES[$userfile];
	
		$vW='125';
		$vH='125';
	
		$imageData=array(
				'userfile'=>$userfile,
				'imagearray'=>$image,
				'imagepath'=>'./assets/img/data/logo/',
				'allowedtype'=>'jpg|png|gif|jpeg',
				'overwrite'=>'true',
				'removespace'=>'true',
				'customefilename'=>'',     		//do not use extension if not need leave blank
				'namewithtime'=>'yes', 			//time(image_121326.jpg)at last of file name if not need leave blank
				'separator'=>'-', 				//format - image_121326.jpg (.)not allowed, if not require leave blank
				'prefix'=>'yp_',				//format my_image_121326.jpg , if not require leave blank
				'errmessage'=>'',               // If blank default message will shown
				'sucessmessage'=>'',            // If blank default message will shown
				'createthumb'=>'yes',
				'thumbwidth'=>$vW,
				'thumbheight'=>$vH,
				'thumbpath'=>'' 				// Dont write thumb folder name in path
	
		);
	
		$uploadData=$this->member_model->upload($imageData);
	
	
		$id = $this->input->post('post_id');
	
		$data=array(
	
				//'id'=>$listing_id,
				'logo'=>$uploadData['data'],
	
		);
	
		if ($uploadData['data']  == TRUE ) {
	
	
			$logo = $this->member_model->post_logo($post_id);
	
			if ($logo->logo != 'no-logo.png') {
				$f = BASEPATH.'../assets/img/data/logo/' . $logo->logo;
				unlink($f);
			}
			$this->db->where('id', $id);
			$this->db->update('post',$data);
			$msg = "<div class='alert alert-success'> Logo Uploded Sucessfully!... </div>";
			$this->session->set_flashdata('message', $msg);
			redirect('secure/listing/logo/'.$post_id);
		} else {
			$msg = "<div class='alert alert-success'> Invalid...! </div>";
			$this->session->set_flashdata('message', $msg);
			redirect('secure/listing/logo/'.$post_id);
			exit();
	
		}
	}
	
	function photo($post_id=0)
	{
		
		$data['post_id'] = $post_id;
		
		$data['mode'] = "IMG";
		
		$data['post'] = getPK('post',$post_id);
		$data['photos'] = $this->member_model->getGallerydata($post_id,'photo');
		$this->template->build('listing/gallery',$data);
	
	
	}
	
	function uploader()
	{
		for($i=0 ; $i<count($_FILES["gallery"]["name"]) ; $i++){
			if($_FILES["gallery"]["name"][$i] != ''){ // don't insert if file name empty
				//$dataType = mysql_real_escape_string($_POST["dataType"][$i]);
				$title = mysql_real_escape_string($_POST["gallery_title"][$i]);
	
				$fileData = pathinfo($_FILES["gallery"]["name"][$i]);
	
				$post_id = $this->input->post('post_id');
				$term = 'photo';
				$caption = 'Photo';
	
				$fileName = uniqid() . '.' . $fileData['extension'];
				$target_path = "assets/img/data/photo/" . $fileName;
	
				while(file_exists($target_path)){
					$fileName = uniqid() . '.' . $fileData['extension'];
					$target_path = "assets/img/data/photo/" . $fileName;
				}
	
				if (move_uploaded_file($_FILES["gallery"]["tmp_name"][$i], $target_path)){    // The file is in the images/gallery folder.
					// Insert record into database by executing the following query:
	
	
	
					$sql="INSERT INTO gallery (title, value, post_id, term, caption) "."VALUES('$title','$fileName','$post_id','$term','$caption')";
					$this->db->query($sql);
	
	
					//redirect('member/business/photo/'.$post_id);
	
					//echo "The image {$_FILES['gallery']['name'][$i]} was successfully uploaded and added to the gallery<br />
	
					//<a href='index.php'>Add another image</a><br />";
	
					//	redirect('member/business/photo/'.$post_id);
					$this->photo($post_id);
				}
				else
				{
					$this->photo($post_id);
				}
			}
			}
		}
		
		function video($post_id=0){
			
			$data['post_id'] = $post_id;
			$data['mode'] = "VIDEO";
			$data['post'] = getPK('post',$post_id);
			$data['videos'] = $this->member_model->getGallerydata($post_id,'video');
		
			$this->template->build('listing/gallery',$data);
		}
		
		
		
		
		
		function upload_video($post_id=0){
		
			$this->form_validation->set_rules('video','Video','required|xss_clean');
			$post_id = $this->input->post('post_id');
			$video = $this->input->post('video');
			$len=strlen($video);
			$pos=strrpos($video, '=');
			$urlid= substr($video,$pos+1);
		
			if($this->form_validation->run() == TRUE){
		
				$post_data = array(
		
						'post_id' => $post_id,
						'term' => 'video',
						'value' => $urlid,
						'caption' => 'Video'
		
				);
		
				//	var_dump($post_data);die();
		
				$this->db->insert('gallery',$post_data);
				$msg = "<div class='alert alert-success'> Video Uploded Sucessfully!... </div>";
				$this->session->set_flashdata('message', $msg);
				redirect('secure/listing/video/'.$post_id);
		
			}else{
				$msg = "<div class='alert alert-warning'> Invalid...! </div>";
				$this->session->set_flashdata('message', $msg);
				redirect('secure/listing/video/'.$post_id);
				exit();
		
			}
		}
		
		
		
}